package logic

import (
	"context"
	"home-mgr/homerpc/homerpcclient"
	"home-mgr/model"

	"home-mgr/homerpc/homerpc"
	"home-mgr/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PreListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPreListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PreListLogic {
	return &PreListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PreListLogic) PreList(in *homerpc.PreListRequest) (*homerpc.PreListResponse, error) {
	// todo: add your logic here and delete this line

	var pres []model.PreUser
	tx := model.DB.Debug().
		Model(model.Pre{}).
		Select("pres.*, users.name as user_name, houses.address as house_address").
		Joins("left join houses on houses.id = pres.house_id").
		Joins("left join users on users.id = houses.user_id")
	if in.TimeOrder == 1 {
		tx = tx.Order("time asc")
	}
	if in.TimeOrder == 2 {
		tx = tx.Order("time desc")
	}
	tx.Find(&pres)

	var preList []*homerpc.PreList
	for _, pre := range pres {

		list := homerpcclient.PreList{
			UserId:  int64(pre.UserId),
			HouseId: int64(pre.HouseId),
			Status:  pre.Status,
			Time:    pre.Time,
		}
		preList = append(preList, &list)
	}
	return &homerpc.PreListResponse{
		List: preList,
	}, nil
}
